package com.example.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.usercenter.contant.UserContant;
import com.example.usercenter.model.User;
import com.example.usercenter.model.request.UserLoginRequest;
import com.example.usercenter.model.request.UserRegisterRequest;
import com.example.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Resource
    private UserService userService;
    
    @PostMapping("/register")
    public Long register(@RequestBody UserRegisterRequest registerRequest){
        if (registerRequest == null){
            return null;
        }
        String userAccount = registerRequest.getUserAccount();
        String userPassword = registerRequest.getUserPassword();
        String checkPassword = registerRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            return null;
        }
        return userService.userRegister(userAccount,userPassword,checkPassword);
    }
    
    @PostMapping("/login")
    public User login(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request){
        if (loginRequest == null){
            return null;
        }
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            return null;
        }
        return userService.userLogin(userAccount,userPassword,request);
    }
    
    @GetMapping("/search")
    public List<User> getUserByAccount(String userAccount,HttpServletRequest request){
        if (true){
            return userService.list();
        }
        List<User> list = new ArrayList<>();
        if (StringUtils.isBlank(userAccount)){
            return list;
        }
        User user = (User) request.getSession().getAttribute(UserContant.USER_LOGIN_STATUS);
        if (user == null){
            // 未登录
            return list;
        }
        if (user.getUserRole() != UserContant.ROLE_ADMIN){
            // 非管理员，权限不够
            return list;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_account", userAccount);
        List<User> userList = userService.list(queryWrapper);
        // 脱敏
        userList.stream().map(u -> {
            return userService.getSafetyUser(u);
        }).collect(Collectors.toList());
        return userList;
    }
}
